# coding: utf-8
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QWidget, QStackedWidget, QVBoxLayout
from qeventmanager import qevent_manager
from qfluentwidgets import SegmentedWidget, SingleDirectionScrollArea

from api import CourseAPI
from components import BookCard, GridLayout, Alert, SlidingStackedWidget

from .item_scroll_area import ItemScrollArea, TermItemScrollArea



class CourseInterface(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.verticalLayout = QVBoxLayout(self)
        self.pivot = SegmentedWidget(self)
        self.stackedWidget = SlidingStackedWidget(self)
        self.courseWidget = ItemScrollArea(self)
        self.allCourseWidget = TermItemScrollArea(self)
        self.__initWidgets()

    def __initWidgets(self):
        self.pivot.addItem('current_course', '当前课程')
        self.pivot.addItem('all_course', '所有课程')
        self.stackedWidget.addWidget(self.courseWidget)
        self.stackedWidget.addWidget(self.allCourseWidget)
        self.pivot.setCurrentItem('current_course')

        self.__initLayout()

        self.pivot.currentItemChanged.connect(self.onPivotChanged)

    def __initLayout(self):
        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.setContentsMargins(11, 45, 11, 11)
        self.verticalLayout.addWidget(self.pivot, 0, Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.addWidget(self.stackedWidget, 1)

        self.getCourseData()

    def getCourseData(self):
        qevent_manager.addTask(CourseAPI.courseData, slot=self.onShowCourseData)

    def onShowCourseData(self, result: dict):
        hr = result['hr']
        data = result['data']
        message = result['message']
        Alert.success(message)
        if hr != 0:
            return
        for item in data:
            self.allCourseWidget.addBookCard(item)
            if item['learnStatusName'] == '在修':
                self.courseWidget.addBookCard(item)

    def onPivotChanged(self, routeKey: str):
        mapping = {
            'current_course': self.courseWidget,
            'all_course': self.allCourseWidget,
        }
        self.stackedWidget.setCurrentWidget(mapping[routeKey])
